package org.sfnelson.sk.client;

import org.sfnelson.sk.client.data.User;
import org.sfnelson.sk.client.event.Created;
import org.sfnelson.sk.client.event.Joined;
import org.sfnelson.sk.client.event.Left;
import org.sfnelson.sk.client.event.ReceivedLoot;
import org.sfnelson.sk.client.rpc.EventListener;
import org.sfnelson.sk.client.rpc.EventManager;

import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.ComplexPanel;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.Widget;

public class LogPanel extends Composite implements EventListener {

	private final Panel contents;
	private int count = 0;

	public LogPanel() {
		Panel widget = new FlowPanel();
		initWidget(widget);
		setStyleName("log");

		Panel container = new FlowPanel();
		widget.add(container);
		container.setStyleName("container");

		contents = new StackPanel();
		container.add(contents);
		contents.addStyleName("contents");

		EventManager.impl().addListener(this);
	}

	public void onCreated(Created event) {
		User user = event.user;
		contents.add(new Entry(user.getName() + " added at "
				+ event.user.random(++count)+ " (1-" + count + ")"));
	}

	public void onJoined(Joined event) {
		User user = event.user;
		contents.add(new Entry(user.getName() + " joined the raid group."));
	}

	public void onLeft(Left event) {
		User user = event.user;
		contents.add(new Entry(user.getName() + " left the raid group."));
	}

	public void onReceivedLoot(ReceivedLoot event) {
		User user = event.user;
		int loot = (event.loot != null) ? event.loot.getId() : 0;
		contents.add(new Entry(user.getName()
				+ " received loot <a href='http://www.wowhead.com/?item="
				+ loot + "'>" + loot + "</a> (" + event.reason + ")"));
	}

	private class Entry extends Composite {
		public Entry(String value) {
			HTML label = new HTML(value);
			label.setStyleName("entry");
			initWidget(label);
		}
	}

	private class StackPanel extends ComplexPanel {

		public StackPanel() {
			setElement(DOM.createElement("DIV"));
		}

		@Override
		public void add(Widget w) {
			insert(w, getElement(), 0, true);
		}

	}
}
